<!DOCTYPE html>
<html>
	<head>
		<meta charset="utf-8">
		<title></title>
	</head>
	<body>
		<script type="text/javascript">
			//二叉树层次遍历
			function TreeNode(val, left, right) {
				this.val = (val === undefined ? 0 : val)
				this.left = (left === undefined ? null : left)
				this.right = (right === undefined ? null : right)
			}
			let r = new TreeNode(1,
				new TreeNode(2,
					new TreeNode(4, null, null),
					new TreeNode(5, null, null)),
				new TreeNode(3,
					new TreeNode(6, null, null),
					new TreeNode(7, null, null)));
			var levelOrder = function(root) {
				if (!root) return []
				const q = [
					[root, 0]
				] // 记录节点和层级
				const res = []
				while (q.length) {
					const [n, level] = q.shift()
					if (!res[level]) {
						res.push([n.val])
					} else {
						res[level].push(n.val)
					}
					if (n.left) q.push([n.left, level + 1])
					if (n.right) q.push([n.right, level + 1])
				}
				return res
			};
			console.log(levelOrder(r));
		</script>
	</body>
</html>
